package org.sidora.strata.context.types;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.lang.reflect.Field;
import javax.swing.JPopupMenu;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.MeasureSet;
import org.sidora.core.context.Context;
import org.sidora.core.context.Stratum;
import org.sidora.strata.SidoraTools;
import org.sidora.strata.Storage;

/**
 * Top component which displays something.
 */

final class StratumTypeTopComponent extends TopComponent {
    
    private static StratumTypeTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    
    private static final String PREFERRED_ID = "StratumTypeTopComponent";
    
    private StratumTypeTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(StratumTypeTopComponent.class, "CTL_StratumTypeTopComponent"));
        setToolTipText(NbBundle.getMessage(StratumTypeTopComponent.class, "HINT_StratumTypeTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextFieldComposition = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldColour = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldInclusions = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldCompaction = new javax.swing.JTextField();
        jTextFieldSlope = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jFormattedTextFieldLength = new javax.swing.JFormattedTextField();
        jFormattedTextFieldWidth = new javax.swing.JFormattedTextField();
        jFormattedTextFieldHeight = new javax.swing.JFormattedTextField();

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Composition:");

        jTextFieldComposition.setEditable(false);
        jTextFieldComposition.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldCompositionMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Colour:");

        jTextFieldColour.setEditable(false);
        jTextFieldColour.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldColourMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, "Compaction:");

        jTextFieldInclusions.setEditable(false);
        jTextFieldInclusions.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldInclusionsMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, "Inclusions:");

        jTextFieldCompaction.setEditable(false);
        jTextFieldCompaction.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldCompactionMouseClicked(evt);
            }
        });

        jTextFieldSlope.setEditable(false);
        jTextFieldSlope.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldSlopeMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, "Slope:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Measures"));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, "Length:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel7, "Width:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel8, "Height:");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel5)
                    .add(jLabel7)
                    .add(jLabel8))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jFormattedTextFieldHeight, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextFieldWidth, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jFormattedTextFieldLength, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
        );

        jPanel1Layout.linkSize(new java.awt.Component[] {jFormattedTextFieldHeight, jFormattedTextFieldLength, jFormattedTextFieldWidth}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(jFormattedTextFieldLength, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel7)
                    .add(jFormattedTextFieldWidth, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel8)
                    .add(jFormattedTextFieldHeight, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel2)
                    .add(jLabel1)
                    .add(jLabel3)
                    .add(jLabel4)
                    .add(jLabel6))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jTextFieldColour, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)
                    .add(jTextFieldComposition, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)
                    .add(jTextFieldSlope, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)
                    .add(jTextFieldInclusions, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)
                    .add(jTextFieldCompaction, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE))
                .add(25, 25, 25)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jTextFieldComposition, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel1))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jTextFieldColour, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel2))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jTextFieldCompaction, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel3))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jTextFieldInclusions, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel4))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jTextFieldSlope, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel6)))
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    
    private void jTextFieldSlopeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldSlopeMouseClicked
        try {
            Field fiel = Stratum.class.getDeclaredField("slope");
            jPopupMenu = SidoraTools.generatePopupMenuCategory(Storage.getContext(), fiel, jTextFieldSlope);
            jPopupMenu.show(jTextFieldSlope,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jTextFieldSlopeMouseClicked
    
    private void jTextFieldCompactionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldCompactionMouseClicked
        try {
            Field fiel = Stratum.class.getDeclaredField("compaction");
            jPopupMenu = SidoraTools.generatePopupMenuCategory(Storage.getContext(), fiel, jTextFieldCompaction);
            jPopupMenu.show(jTextFieldCompaction,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jTextFieldCompactionMouseClicked
    
    private void jTextFieldInclusionsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldInclusionsMouseClicked
        try {
            Field fiel = Stratum.class.getDeclaredField("inclusions");
            jPopupMenu = SidoraTools.generatePopupMenuCategorys(Storage.getContext(), fiel, jTextFieldInclusions);
            jPopupMenu.show(jTextFieldInclusions,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jTextFieldInclusionsMouseClicked
    
    private void jTextFieldColourMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldColourMouseClicked
        try {
            Field fiel = Stratum.class.getDeclaredField("colour");
            jPopupMenu = SidoraTools.generatePopupMenuCategory(Storage.getContext(), fiel, jTextFieldColour);
            jPopupMenu.show(jTextFieldColour,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jTextFieldColourMouseClicked
    
    private void jTextFieldCompositionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldCompositionMouseClicked
        try {
            Field fiel = Stratum.class.getDeclaredField("composition");
            jPopupMenu = SidoraTools.generatePopupMenuCategory(Storage.getContext(), fiel, jTextFieldComposition);
            jPopupMenu.show(jTextFieldComposition,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jTextFieldCompositionMouseClicked
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFormattedTextField jFormattedTextFieldHeight;
    private javax.swing.JFormattedTextField jFormattedTextFieldLength;
    private javax.swing.JFormattedTextField jFormattedTextFieldWidth;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextFieldColour;
    private javax.swing.JTextField jTextFieldCompaction;
    private javax.swing.JTextField jTextFieldComposition;
    private javax.swing.JTextField jTextFieldInclusions;
    private javax.swing.JTextField jTextFieldSlope;
    // End of variables declaration//GEN-END:variables
    private JPopupMenu jPopupMenu;
    
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized StratumTypeTopComponent getDefault() {
        if (instance == null) {
            instance = new StratumTypeTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the StratumTypeTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized StratumTypeTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find StratumType component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof StratumTypeTopComponent) {
            return (StratumTypeTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    public void componentOpened() {
        // TODO add custom code on component opening
    }
    
    public void componentClosed() {
        // TODO add custom code on component closing
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return StratumTypeTopComponent.getDefault();
        }
    }
    
    public void saveStratumFields(){
        Stratum stratum = (Stratum) Storage.getContext();
        
        //TODO Guardar Mesures
        if (stratum != null){
            if (stratum.getMeasures() == null)
                stratum.setMeasures(new MeasureSet());
            
            try {
                stratum.getMeasures().setHeight(Double.parseDouble(jFormattedTextFieldHeight.getText()));
            } catch (NumberFormatException ex) {
                ex.printStackTrace();
            }
            try {
                stratum.getMeasures().setWidth(Double.parseDouble(jFormattedTextFieldWidth.getText()));
            } catch (NumberFormatException ex) {
                ex.printStackTrace();
            }
            try {
                stratum.getMeasures().setLength(Double.parseDouble(jFormattedTextFieldLength.getText()));
            } catch (NumberFormatException ex) {
                ex.printStackTrace();
            }
            
            
        }
    }
    
    public void fillItems(){
        emptyItems();
        Stratum stratum = (Stratum) Storage.getContext();
        
        if (stratum.getComposition() != null){
            jTextFieldComposition.setText(stratum.getComposition().toString());
        }
        
        if (stratum.getColour() != null){
            jTextFieldColour.setText(stratum.getColour().toString());
        }
        
        if (stratum.getCompaction() != null){
            jTextFieldCompaction.setText(stratum.getCompaction().toString());
        }
        
        if (stratum.getSlope() != null){
            jTextFieldSlope.setText(stratum.getSlope().toString());
        }
        
        if (stratum.getInclusions() != null){
            if (stratum != null){
                jTextFieldInclusions.setText(SidoraTools.TreeSet2String(stratum.getInclusions()));
            }
        }
        
        
        if (stratum.getMeasures() != null){
            MeasureSet ms = stratum.getMeasures();
            if (ms != null){
                jFormattedTextFieldHeight.setText(String.valueOf(ms.getHeight()));
                jFormattedTextFieldLength.setText(String.valueOf(ms.getLength()));
                jFormattedTextFieldWidth.setText(String.valueOf(ms.getWidth()));
            }
        }
    }
    
    
    public void emptyItems(){
        jTextFieldComposition.setText("");
        jTextFieldColour.setText("");
        jTextFieldCompaction.setText("");
        jTextFieldSlope.setText("");
        jTextFieldInclusions.setText("");
        jFormattedTextFieldHeight.setText("");
        jFormattedTextFieldLength.setText("");
        jFormattedTextFieldWidth.setText("");
    }
}
